package io.github.fb513.transport.handler;

import com.fasterxml.jackson.databind.JsonNode;
import io.github.fb513.common.model.MessageInfo;
import io.github.fb513.transport.util.JsonUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class WebSocketMessageDecoder extends MessageToMessageDecoder<TextWebSocketFrame> {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg, List<Object> out) {
        String text = msg.text();
        JsonNode jsonNode = JsonUtils.parseJsonToJsonNode(text);
        MessageInfo<JsonNode> message = new MessageInfo<>();
        message.setHeader(JsonUtils.convertToPojo(jsonNode.get("header"), MessageInfo.Header.class));
        message.setContent(jsonNode.get("content"));
        out.add(message);
    }
}
